<?php

namespace app\model\v1\recovery;

use app\model\user\User;
use crmeb\traits\ModelTrait;
use think\facade\Db;
use think\Model;
use think\Exception;

class RecoveryProductQuote extends Model
{
    use ModelTrait;


    protected $updateTime = false;
    protected $createTime = false;

    public function user()
    {
        return $this->hasOne(User::class, 'uid', 'uid');
    }


    public function shop()
    {
        return $this->hasOne(User::class, 'uid', 'shop_id');
    }

    public function product()
    {
        return $this->hasOne(RecoveryProduct::class, 'id', 'product_id');
    }


    /**
     * 用户新增报价
     * @param $param
     * @return int|string
     */
    public static function createOne($param = [])
    {
        $add = [
            'uid'           => $param['user_id'],
            'product_id'    => $param['product_id'],
            'quote_price'   => $param["quote_price"],
            'shop_id'       => $param["shop_id"],
            'create_time'   => time(),
        ];
        $res = self::insert($add);
        return $res;
    }


    /**
     * 我卖出的 - 列表同意按钮
     * @param $param
     * @return array
     * @throws \think\exception\PDOException
     */
    public static function enableQuote($param = [])
    {
        $product_on_sale = Db::name("recovery_product")->where("id", $param["product_id"])->value("on_sale") ?? 0;
        if($product_on_sale == 3) Throw new \Exception("商家已下架该宝贝！");
        if($product_on_sale == 2) Throw new \Exception("宝贝已下架！");
		    $product_quote_status = Db::name("recovery_product_quote")->where("id", $param["quote_id"])->value("status");

	    if ($product_quote_status>1){
		    Throw new \Exception("当前状态无法同意报价！");
	    }
        try {
            Db::startTrans();

            if($param["is_agree"] == 1){  // 同意
                //更新商品状态为交易中
                Db::name("recovery_product")->where("id", $param["product_id"])->update(["status" => 3]);
                //更新用户报价状态为待取货
                Db::name("recovery_product_quote")->where("id", $param["quote_id"])->update(["status" => 2, "update_time"=>time()]);
                //更新其它用户报价状态为报价失败
                Db::name("recovery_product_quote")->where("product_id", $param["product_id"])->where("id", "<>", $param["quote_id"])->update(["status" => 5]);
            }else{  //拒绝
                //更新用户报价状态为商家已拒绝
                Db::name("recovery_product_quote")->where("id", $param["quote_id"])->update(["status" => 6]);
            }

            Db::commit();
            return true;
        }catch (\Throwable $e){
            Db::rollback();
            Throw new \Exception($e->getMessage());
            return false;
        }
        return false;
    }


    /**
     * 我买到的 - 确认收货
     * @param $param
     * @return array
     * @throws \think\exception\PDOException
     */
    public static function enableBuyQuote($param = [])
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => ''
        ];

        $quote_status = self::where(["id" => $param["quote_id"]])->value("status") ?? 0;
        if($quote_status == 4) Throw new \Exception("买家已取消！");

        Db::startTrans();
        try {
            //更新商品状态为已售出
            Db::name("recovery_product")->where(["id" => $param["product_id"]])->update(["status" => 4, "is_sold" => 1]);
            //更新用户报价状态为已完成
            Db::name("recovery_product_quote")->where(["id" => $param["quote_id"]])->update(["status" => 3]);
            //商品的其它用户报价删除
            self::delOtherUserQuote($param["product_id"], $param["user_id"]);

            Db::commit();
            $result['status'] = true;
        }catch (\Throwable $e){
            Db::rollback();
            $result['msg'] = $e->getMessage();
            return $result;
        }

        return $result;
    }




    /**
     * 我买到的 - 用户取消交易
     * @param $param
     * @return array
     * @throws \think\exception\PDOException
     */
    public static function cancelBuyQuote($param = [])
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => ''
        ];

        Db::startTrans();
        try {
            //更新商品状态
            Db::name("recovery_product")->where("id", $param["product_id"])->update(["status" => 1, "is_sold" => 0]);
            //更新用户报价状态为已取消

            $quote_status = Db::name("recovery_product_quote")->where("id", $param["quote_id"])->value("status") ?? 0;
            if($quote_status == 4)  throw new \Exception("用户报价已取消！");
            Db::name("recovery_product_quote")->where("id", $param["quote_id"])->update(["status" => 4]);
            //更新其它用户报价状态为已报价
            ////Db::name("recovery_product_quote")->where("product_id", $param["product_id"])->where("id", "<>", $param["quote_id"])->update(["status" => 1]);

            Db::commit();
            $result['status'] = true;
        }catch (\Throwable $e){
            Db::rollback();
            $result['msg'] = $e->getMessage();
            return $result;
        }

        return $result;
    }




    /**
     * 商品的其它的用户报价删除
     * @param $product_id
     * @param $buy_user_id
     * @return RecoveryProductQuote
     */
    public static function delOtherUserQuote($product_id = '', $buy_user_id = '')
    {
        return self::where(function ($query) use ($product_id, $buy_user_id){
                    $query->where('product_id', $product_id);
                    $query->where('uid', '<>', $buy_user_id);
                })->update(["delete_time" => time()]);
    }


    /**
     * 删除订单
     * @param $param
     * @return int|string
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function delBuyQuote($param = [])
    {
        $field = "delete_time";
        if($param["is_buy"] == 1) $field = "buy_delete_time";
        //更新用户报价状态为已取消
        $res = Db::name("recovery_product_quote")->where("id", $param["quote_id"])->update(["{$field}" => time()]);
        return $res;
    }


}